/**
 * Created by yys on 2016/12/15.
 * @description 菜鸟物流打印组件调取
 * @copyright
 */
var socket;
//备注：webSocket 是全局对象，不要每次发送请求丢去创建一个，做到webSocket对象重用，和打印组件保持长连接。
function doConnect(ws_url)
{
    if(isNull(socket)){
        socket = new WebSocket(ws_url);
    }
    //如果是https的话，端口是13529
    //socket = new WebSocket('wss://localhost:13529');
    // 打开Socket
    socket.onopen = function(event)
    {
        // 监听消息
        socket.onmessage = function(event)
        {
            console.log('客户端收到一条消息，',event);
        };
        // 监听Socket的关闭
        socket.onclose = function(event)
        {
            console.log('监听Socket的关闭，',event);
        };
    };
    return socket;
}
/***
 * 获取打印机
 */
function doGetPrinters() {
    var request  = {
        requestID : '12345678901234567890',
        version : '1.0',
        cmd : 'getPrinters'
    };
    socket=doConnect();
    var message=JSON.stringify(request);
    socket.send(message);
    var data=new Array();
    socket.onmessage = function(event,data)
    {
        data=event.data;
        console.log(data);
        return data;
    };
    return data;
}

/***
 *
 * 获取请求的UUID，指定长度和进制,如
 * getUUID(8, 2)   //"01001010" 8 character (base=2)
 * getUUID(8, 10) // "47473046" 8 character ID (base=10)
 * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
 *
 */
function getUUID(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}
/***
 * 构造request对象
 */
function getRequestObject(cmd) {
    var request  = new Object();
    request.requestID=getUUID(8, 16);
    request.version="1.0";
    request.cmd=cmd;
    return request;
}
/***
 * 获取自定义区数据以及模板URL
 * waybillNO 电子面单号
 */
function getCustomAreaData(waybillNO){
    //获取waybill对应的自定义区的JSON object，此处的ajaxGet函数是伪代码
    var jsonObject = ajaxGet(waybillNO);
    var ret = new Object();
    ret.templateURL=jsonObject.content.templateURL;
    ret.data=jsonObject.content.data;
    return ret;
}
/***
 * 获取电子面单Json 数据
 * waybillNO 电子面单号
 */
function getWaybillJson(waybillNO){
    //获取waybill对应的json object，此处的ajaxGet函数是伪代码
    var jsonObject = ajaxGet(waybillNO);
    return jsonObject;
}
/**
 * 弹窗模式配置打印机
 * */

function doGetPrinterConfig() {
    var request  = getRequestObject("printerConfig");
    if(socket==null){
        socket=doConnect();
    }
    socket.send(JSON.stringify(request));
}
/**
 * 打印电子面单
 * printer 指定要使用那台打印机
 * waybillArray 要打印的电子面单的数组
 */
function doPrint(printer,waybillArray)
{
    var request = getRequestObject("print");
    request.task = new Object();
    request.task.taskID = getUUID(8,10);
    request.task.preview = false;
    request.task.printer = printer;
    var documents = new Array();
    documents=[
        {
            documentID : "100000000001",
            contents : [
                //电子面单部分
                {
                    templateURL : "http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=801",
                    signature : "ALIBABACAINIAOWANGLUO",
                    "data": {
                        "recipient": {
                            "address": {
                                "city": "北京市",
                                "detail": "花家地社区卫生服务站三层楼我也不知道是哪儿了",
                                "district": "朝阳区",
                                "province": "北京",
                                "town": "望京街道"
                            },
                            "mobile": "1326443654",
                            "name": "张三",
                            "phone": "057123222"
                        },
                        "routingInfo": {
                            "consolidation": {
                                "name": "杭州",
                                "code": "hangzhou"
                            },
                            "origin": {
                                "code": "POSTB"
                            },
                            "sortation": {
                                "name": "杭州"
                            },
                            "routeCode": "380D-56-04"
                        },
                        "sender": {
                            "address": {
                                "city": "北京市",
                                "detail": "花家地社区卫生服务站二层楼我也不知道是哪儿了",
                                "district": "朝阳区",
                                "province": "北京",
                                "town": "望京街道"
                            },
                            "mobile": "1326443654",
                            "name": "张三",
                            "phone": "057123222"
                        },
                        "shippingOption": {
                            "code": "COD",
                            "services": {
                                "SVC-COD": {
                                    "value": "200"
                                }
                            },
                            "title": "代收货款"
                        },
                        "waybillCode": "9890000160004"
                    }
                },
                //自定义区部分
                {
                    templateURL : "http://cloudprint.cainiao.com/cloudprint/customArea/queryCustomAreaList4Top.json?custom_area_id=642230",
                    data : {
                        "item_name": "我是你要的商品芭比娃娃。。。",
                    }
                }
            ]
        },
        {
            documentID : "100000000001",
            contents : [
                //电子面单部分
                {
                    templateURL : "http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=801",
                    signature : "ALIBABACAINIAOWANGLUO",
                    "data": {
                        "recipient": {
                            "address": {
                                "city": "北京市",
                                "detail": "花家地社区卫生服务站三层楼我也不知道是哪儿了",
                                "district": "朝阳区",
                                "province": "北京",
                                "town": "望京街道"
                            },
                            "mobile": "1326443654",
                            "name": "张三",
                            "phone": "057123222"
                        },
                        "routingInfo": {
                            "consolidation": {
                                "name": "杭州",
                                "code": "hangzhou"
                            },
                            "origin": {
                                "code": "POSTB"
                            },
                            "sortation": {
                                "name": "杭州"
                            },
                            "routeCode": "380D-56-04"
                        },
                        "sender": {
                            "address": {
                                "city": "北京市",
                                "detail": "花家地社区卫生服务站二层楼我也不知道是哪儿了",
                                "district": "朝阳区",
                                "province": "北京",
                                "town": "望京街道"
                            },
                            "mobile": "1326443654",
                            "name": "张三",
                            "phone": "057123222"
                        },
                        "shippingOption": {
                            "code": "COD",
                            "services": {
                                "SVC-COD": {
                                    "value": "200"
                                }
                            },
                            "title": "代收货款"
                        },
                        "waybillCode": "9890000160004"
                    }
                },
                //自定义区部分
                {
                    templateURL : "http://cloudprint.cainiao.com/cloudprint/customArea/queryCustomAreaList4Top.json?custom_area_id=642230",
                    data : {
                        "item_name": "我是你要的商品芭比娃娃。。。",
                    }
                }
            ]
        }
    ];
    for(i=0;i<waybillArray.length;i++) {
        var doc = new Object();
        doc.documentID = waybillArray[i];
        var content = new Array();
        var waybillJson = getWaybillJson(waybillArray[i]);
        var customAreaData = getCustomAreaData(waybillArray[i]);
        content.push(waybillJson,customAreaData);
        doc.content = content;
        documents.push(doc);
    }
    socket.send(JSON.stringify(request));
}
/***
 * 打印一张单
 * @param printer  打印机
 * @param data     打印内容
 * @param templateURL 模板链接
 */
function doOnePrint(printer,data,templateURL) {
    request  = {
        cmd : "print",
        requetID : "12345678901234567890",
        version : "1.0",
        task : {
            taskID : getUUID(8,10),
            preview : false,
            printer : printer,
            documents : [
                {
                    documentID : "9890000076011",
                    contents : [
                        //电子面单部分
                        {
                            templateURL : templateURL,
                            signature : "ALIBABACAINIAOWANGLUO",
                            "data":data
                        }
                    ]
                }
            ]
        }
    };
    doConnect();
    setTimeout(function() {
        socket.send(JSON.stringify(request))
    },2000);
    console.log('连接');
    console.log(socket);
    console.log('打印测试结束');
    return;
}
/**
 * 判断对象是不是null
 * @param object
 * @returns {boolean}
 */
function isNull(object) {
    if(!object ||(typeof(object)=="undefined") ||(object==0)){
        return true;
    }
    return false;
}
function test() {
    doOnePrint();
}
